// app.component.ts

import {Component, OnInit} from '@angular/core';
import {AbstractControl, FormArray, FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';

// 自定义密码验证
function ValidPwd(control: AbstractControl): any {
  const reg = /^\w{6,12}$/;
  if (reg.test(control.value)) {
    // 通过验证时需要返回 null
    return null;
  }
  return {status: 'error', message: '密码格式为数字字母下划线6-12位'};
}


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  name = 'app';

  form: FormGroup;
  friends;
  contactType:number = 0;

  constructor(
    private fb: FormBuilder
  ) {}

  ngOnInit() {
    this.form = this.fb.group({
      name: ['', Validators.required],
      password: ['', [Validators.required, ValidPwd]],
      friends: this.fb.array([this.createFriend()]),
      contact: ['', Validators.required]
    });

    this.friends = this.form.get('friends') as FormArray;
  }

  /**
   * 动态创建表单
   * @returns {FormControl}
   */
  createFriend() {
    return this.fb.control('', Validators.required);
  }

  /**
   * 增加输入框
   */
  addFriend(): void {
    this.friends.push(this.createFriend());

  }

  /**
   * 移除输入框
   * @param {number} i
   */
  removeFriend(i: number): void {
    this.friends.removeAt(i);
  }

  submit() {
    if (this.form.valid) {
      console.log('submitting...');
    } else {
      console.log('form is not valid');
    }
  }

  reset() {
    this.form.reset();
  }
}

